local lua_mongo = _G.lua_mongo
local Config = require("Config")
local Log = require("common.Log")
local Util = require("common.Util")
local PfLogic = require("platform.PfLogic")

-- 是否需要检验账号
local function isNeedCheck(account)
	if Config.IS_USE_GM_CMD == true then
		return
	end

	--[[if PfLogic.isKunTang() or 
       PfLogic.isShouQ() or 
        PfLogic.isFKW() or 
        PfLogic.isQQ() or 
        PfLogic.isAug() or 
        PfLogic.is9377() or 
        PfLogic.isTaptap() or 
        PfLogic.isYingHe() then
		return  -- 某些平台，不开校验
	end
	return true]]
    return
end

local function getReallyAccout(account)
	if not account then return end

	local tb = Util.split(account, "-")
	if #tb < 2 then return end

	local svrIndex = tonumber(tb[1])
	if math.abs(Config.SVR_INDEX - svrIndex) >= 100000 then
		return -- 账号服务器应该一致
	end	
	local index = #tb
	local realAccount = ""
	for i = 2, index do
		if i > 2 then
			realAccount = realAccount .. "-"
		end
		realAccount = realAccount .. tb[i]
	end

	return realAccount
end

function getCalckey(account, timestamp, ip)
	return lua_mongo.md5(account .. timestamp .. ip .. Config.AUTH_KEY)
end

function authCheck(account, authkey, timestamp, ip)
	if isNeedCheck(account) ~= true then
		return true
	end

	local realAccount = getReallyAccout(account)
	if not realAccount then
		Log.write(Log.LOGID_TEST, "auth check fail no realaccount", account, authkey, timestamp, os.time())
		return
	end

	local sec = os.time() - timestamp
	if math.abs(sec) > 86400 then
		Log.write(Log.LOGID_TEST, "auth check fail ts err", account, authkey, timestamp, os.time())
		return
	end

	local calckey = getCalckey(realAccount, timestamp, ip)
	if calckey ~= authkey then
		Log.write(Log.LOGID_TEST, "auth check fail calckey", account, authkey, timestamp, os.time(), calckey)
		return
	end
	return true
end


